package cate.game.role.farm.spicefb;

import cate.common.table.d.*;
import cate.common.table.farm.spicefb.row.SpiceFbStarRow;
import cate.common.table.farm.spicefb.row.SpiceFbChapterRow;
import cate.common.table.farm.spicefb.row.SpiceFbLevelRow;
import cate.common.util.GameResult;
import cate.game.event.spicefb.SpiceFbChapterUnLockedEvent;
import cate.game.mail.po.MailBuilder;
import cate.game.play.part.FightSide;
import cate.game.play.proce.play.PlayPO;
import cate.game.res.MixRes;
import cate.game.res.MixResAdder;
import cate.game.res.MixResItem;
import cate.game.role.Role;
import cate.game.role.farm.AbstractFarm;
import cate.game.role.farm.spicefb.msg.SpiceFbDataResp;
import cate.game.role.farm.spicefb.po.SpiceFbChapter;
import cate.game.role.farm.spicefb.po.SpiceFbLevel;
import cate.game.role.mail.Mail;
import com.fasterxml.jackson.annotation.JsonIgnore;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcResult;

import java.util.HashMap;
import java.util.Map;

@NoteClass("香料副本")
public class SpiceFb extends AbstractFarm {
    @NoteField(value = "已通关的关数")
    public int combatNumPass;

    @NoteField(value = "解锁的章节数", detail = "初始化是1")
    public int chapterOpen;

    @NoteField(value = "香料副本信息", detail = "map<章节id，章节信息>")
    public Map<Integer, SpiceFbChapter> chapterMap;

    @NoteField(value = "今日的扫荡次数")
    public int todayMopTimes;

    @NoteField(value = "今日通关次数")
    public int todayPassed;

    @NoteField("今日购买次数")
    public int todayBuyTimes;

    @NoteField(value = "剩余挑战次数", detail = "购买之后才会增加，跨天也不清除，前端优先判断今日通关次数字段")
    public int remainBuyTimes;

    @NoteField(value = "星数奖励")
    public Map<Integer, Boolean> starRewardMap;

    @NoteField(value = "章节奖励")
    public Map<Integer, Boolean> charpterRewardMap;

    @NoteField("是否领取每日奖励")
    public boolean todayRewardGot;

    @Override
    public void initialize(Role role) {
        super.initialize(role);
        if (starRewardMap == null) {
            starRewardMap = new HashMap<>();
        }
        if (charpterRewardMap == null) {
            charpterRewardMap = new HashMap<>();
        }
        if (chapterMap == null) {
            chapterMap = new HashMap<>();
        }
        chapterMap.entrySet().removeIf(e -> e.getValue().chapter == 0);
        chapterMap.values().forEach(a -> a.initialize(role));
    }

    @Override
    public void onEnter(){
        super.onEnter();
        checkOpen();
        if (isOpen()) {
            checkUnLock();
        }
    }

    /** 检测关卡章节解锁 */
    public synchronized void checkUnLock() {
        boolean unlock = getChapter(chapterOpen).unlockNextChapter();
        if (unlock) {
            // 先看看有没有下一章了
            SpiceFbChapterRow row = role.getGame().table.spiceFb.chapter.get(chapterOpen + 1);
            if (row == null) {
                return;
            }
            chapterOpen++;
            getChapter(chapterOpen);
            role.sendNow(new SpiceFbDataResp(this));
            SpiceFbChapterUnLockedEvent.current().ifPresent(SpiceFbChapterUnLockedEvent::setUnlocked);
        }
    }

    /** 获取章节(一定能获取) */
    @JsonIgnore
    public synchronized SpiceFbChapter getChapter(int chapterId) {
        SpiceFbChapter chapter = chapterMap.get(chapterId);
        if (chapter == null) {
            chapter = new SpiceFbChapter(chapterId);
            chapter.initialize(role);
            if (chapterId > 0) {
                chapterMap.put(chapterId, chapter);
            }
        }
        return chapter;
    }

    /** 获取累计的挑战星星数量 */
    @JsonIgnore
    public int getStar() {
        int star = 0;
        if (chapterMap != null && chapterMap.size() > 0) {
            for (SpiceFbChapter chapter : chapterMap.values()) {
                chapter.updateChapter();
                star += chapter.star;
            }
        }
        return star;
    }

    /** 挑战副本 */
    public GameResult<Void> challenge(int combatNum) {
        GameResult<Void> r = new GameResult<>();
        if(!isOpen()){
            return r.fail("功能未开启");
        }
        if (fighting) {
            return r.fail("当前正在战斗中");
        }
        if (combatNum > this.combatNumPass + 1) {
            return r.fail("请先挑战之前的关卡");
        }
        SpiceFbLevelRow levelRow = role.getGame().table.spiceFb.level.get(combatNum);
        if (levelRow == null) {
            return r.fail("所选关卡不存在");
        }
        SpiceFbChapter chapter = getChapter(levelRow.chapter);
        if (chapter == null) {
            return r.fail("关卡所在章节不存在");
        }
        SpiceFbLevel level = chapter.getLevel(combatNum);
        boolean first = level == null || !level.pass;
        boolean freeNone = first && todayPassed >= GDSpiceFb.DAILY_PASSED_TIMES;
        // 判断挑战次数是否够用
        if(freeNone && remainBuyTimes <= 0){
            return r.fail("挑战次数不足");
        }
        // 挑战模式
        EcResult<FightSide> fsResult = role.getGame().fight.side.createFightSideByCode(GDFight.Team.B, levelRow.monsterConf);
        if (!fsResult.ok()) {
            return r.fail(fsResult.message);
        }
        SpiceFbFTC context = new SpiceFbFTC(role, levelRow, freeNone);
        context.funcId = getFightFuncId();
        context.playStory.level = combatNum;
        EcResult<PlayPO> fightRes =  role.getGame().play.startByRole(role, context, fsResult.data);
        if (!fightRes.ok()) {
            return r.fail(fightRes.message);
        }
        this.fighting = true;
        role.getHistory().action.spiceFbChallenge();
        role.getHistory().action.spiceFbChallengeOrMop();
        return r.success();
    }

    @Override
    public int getFightFuncId() {
        return GDFunc.SPICE_FB;
    }

    @Override
    public int getFuncId() {
        return GDFunc.SPICE_FB;
    }

    @Override
    public void onAfterOpen() {
        noticeUpdate();
    }

    public void noticeUpdate(){
        if(isOpen()){
            checkUnLock();
            if(chapterOpen > 0){
                role.sendNow(new SpiceFbDataResp(this));
            }
        }
    }

    @Override
    public void onDaySpan(boolean silence){
        if(!isOpen()){
            return;
        }
        if (!todayRewardGot) {
            SpiceFbStarRow row = role.getGame().table.spiceFb.star.getStarRow(getStar());
            if (row != null) {
                Mail mail = new MailBuilder()
                        .setContentId(GDMail.Tid.SPICE_FB_DAILY_REWARD)
                        .setOperation(GDOperation.SPICE_FB_DAILY_RWD)
                        .setReward(new MixRes(row.dailyRewardStr))
                        .build();
                role.getMail().add(mail);
            }
        }
        todayMopTimes = 0;
        todayPassed = 0;
        todayRewardGot = false;
        todayBuyTimes = 0;
        checkUnLock();
        if(!silence){
            noticeUpdate();
        }
    }

    public GameResult<Void> getStarReward(int tid){
        GameResult<Void> r = new GameResult<>();
        if(!isOpen()){
            return r.fail("功能未开启");
        }
        SpiceFbStarRow boxRow = role.getGame().table.spiceFb.star.get(tid);
        if (boxRow == null) {
            return r.fail("宝箱不存在");
        }
        Boolean got = starRewardMap.get(boxRow.id);
        if (got != null) {
            return r.fail("奖励已经被领取");
        }
        if (getStar() < boxRow.star) {
            return r.fail("未达到宝箱的领取要求");
        }
        starRewardMap.put(boxRow.id, true);
        new MixResAdder()
                .setSendMailWhenFull(true)
                .setRes(boxRow.rewardStr)
                .setDialogReward(true)
                .exe(role);
        noticeUpdate();
        return r;
    }

    public GameResult<Void> getChapterReward(int chapter) {
        GameResult<Void> r = new GameResult<>();
        SpiceFbChapterRow chapterRow = role.getGame().table.spiceFb.chapter.get(chapter);
        if (chapterRow == null) {
            return r.fail("错误的章节");
        }
        return getChapter(chapter).getChapterReward();
    }

    @JsonIgnore
    public GameResult<Void> getDailyReward() {
        GameResult<Void> r = new GameResult<>();
        if (todayRewardGot) {
            return r.fail("今日已领取每日奖励");
        }
        SpiceFbStarRow row = role.getGame().table.spiceFb.star.getStarRow(getStar());
        if (row == null) {
            return r.fail("没有奖励可以领取");
        }
        todayRewardGot = true;
        new MixResAdder()
                .setSendMailWhenFull(true)
                .setDialogReward(true)
                .setRes(row.dailyRewardStr)
                .exe(role);
        noticeUpdate();
        return r;
    }

    public GameResult<Void> bugChallengeTimes() {
        GameResult<Void> r = new GameResult<>();
        if (todayBuyTimes >= GDSpiceFb.BUY_TIMES) {
            return r.fail("今日购买次数不足");
        }
        GameResult<MixResItem> buyRes = new MixRes(GDSpiceFb.BUY_CONSUME_STR).consume(role);
        if (!buyRes.ok()) {
            role.getGame().notice.tipResItem(role, buyRes.data);
            return r.fail(buyRes);
        }
        remainBuyTimes ++;
        todayBuyTimes ++;
        noticeUpdate();
        return r;
    }
}
